package org.example.dobs.demo.kafka;
import org.apache.kafka.clients.producer.*;
import java.util.Properties;

public class KafkaProducerExample {
    public static void main(String[] args) {
        // 配置生产者属性
        Properties props = new Properties();
        props.put("bootstrap.servers", "localhost:9092"); // Kafka 服务器地址
        props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");

        // 创建生产者实例
        Producer<String, String> producer = new KafkaProducer<>(props);

        // 定义要发送的消息
        String topic = "test_topic";
        String key = "key1";
        String value = "Hello, Kafka!";

        // 创建消息记录
        ProducerRecord<String, String> record = new ProducerRecord<>(topic, key, value);

        // 发送消息
        producer.send(record, new Callback() {
            @Override
            public void onCompletion(RecordMetadata metadata, Exception exception) {
                if (exception != null) {
                    System.err.println("消息发送失败: " + exception.getMessage());
                } else {
                    System.out.printf("消息发送成功，分区: %d, 偏移量: %d%n", metadata.partition(), metadata.offset());
                }
            }
        });

        // 关闭生产者
        producer.close();
    }
}
